package com.gulimall.authserver.controller;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.gulimall.authserver.feign.MemberFeignService;
import com.gulimall.common.constrant.AuthServerConstant;
import com.gulimall.common.to.AuthSocialUserTo;
import com.gulimall.common.utils.R;
import com.gulimall.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kkk
 * @date 2022/7/31
 */
@Controller
@Slf4j
public class OAuth2Controller {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;
    @Value("${oauth2.gitee.client_secret}")
    private String client_secret;
    @Value("${oauth2.gitee.client_id}")
    private String client_id;

    @GetMapping("/oauth2/gitee/success")
    public String gitee(@RequestParam String code, HttpSession session) {
        OkHttpClient client = new OkHttpClient.Builder().build();

        Map<String, Object> param = new HashMap<>();

        String paramJson = JSONObject.toJSONString(param);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), paramJson.getBytes());

        Request request = new Request.Builder().url(String.format("https://gitee.com/oauth/token?grant_type" +
                "=authorization_code&code=%s&client_id=%s&redirect_uri=http://auth.gulimall.com/oauth2/gitee" +
                "/success&client_secret=%s", code, client_id, client_secret)).post(requestBody).build();

        try {
            Response response = client.newCall(request).execute();
            if (response.code() == HttpURLConnection.HTTP_OK) {
                String string = response.body().string();
                AuthSocialUserTo socialUser = JSONObject.parseObject(string).to(new TypeReference<AuthSocialUserTo>() {
                });
                log.info("请求获取到的值为 " + socialUser);
                //调用远程服务 登录
                R r = memberFeignService.memberOAuthLogin(socialUser);
                if (r.getResult() == 0) {
                    MemberRespVo respVo = JSONObject.parseObject(JSONObject.toJSONString(r.get("data")),
                            MemberRespVo.class);
                    session.setAttribute(AuthServerConstant.LOGIN_INFO, respVo);

                    return "redirect:http://gulimall.com";
                } else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        //登录成功调回首页
        return "http://gulimall.com";
    }
}
